import * as asyncWx from "../../utils/asyncWx.js";
import {request} from "../../request/index.js";
Page({
    data:{
        address:{},
        carts:[],
        totalPrice:0,
        totalNum:0
    },
    //页面显示隐藏调用的回调函数
    onShow(){
        let address=wx.getStorageSync("address");
        let carts=wx.getStorageSync("carts") || [];
        carts=carts.filter((item)=>{
            return item.checked;
        });
        let totalPrice=0;
        let totalNum=0;
        carts.forEach((item)=>{
            totalPrice+=item.num*item.goods_price;
            totalNum+=item.num;
        });
        this.setData({
            carts,
            totalPrice,
            totalNum,
            address
        });
    },
    //点击支付按钮事件监听
    async handlePay(){
        const token=wx.getStorageSync("token");
        if(!token){
            wx.navigateTo({
                url:"/pages/auth/index"
            });
        }else{
            try{//支付过程代码只能模拟
                // const header={Authorization:token};
                const order_price=this.data.totalPrice;
                const consignee_addr=this.data.address.provinceName+this.data.address.cityName+this.data.address.countyName+this.data.address.detailInfo;
                let goods=[];
                this.data.carts.forEach((item)=>{
                    goods.push({
                        goods_id:item.goods_id,
                        goods_number:item.num,
                        goods_price:item.goods_price
                    });
                });
                const orderParams={order_price,consignee_addr,goods};
                const res=await request({url:"/my/orders/create",method:"post",data:orderParams});
                // console.log(res);
                // const {pay}= await request({url:"/my/orders/req_unifiedorder",method:"post",data:{order_number:res.order_number}});
                // await asyncWx.requestPayment(pays);
                // const result=await request({url:"/my/orders/chkOrder",method:"post",data:{order_number:res.order_number}});
                await asyncWx.showToast({title:"支付成功"});
                //在缓存中移除已经支付过的商品
                let newCart=wx.getStorageSync("carts");
                newCart=newCart.filter((item)=>{
                    return !item.checked;
                });
                wx.setStorageSync("carts",newCart);
                wx.navigateTo({
                    url:"/pages/order/index?type=1"
                });
            }catch(err){
                await asyncWx.showToast({title:"支付失败"});
                console.log(err);
            };
        };
    }
})